import axios, {
  type AxiosInstance,
  type AxiosRequestConfig,
  type AxiosResponse,
  type InternalAxiosRequestConfig,
  type AxiosError,
} from "axios";
import { useUserStore } from "@/stores/user";
export interface ResponseData<T = any> {
  code: number;
  data: T;
  message: string;
  timestamp?: number;
}

export interface RequestConfig extends AxiosRequestConfig {
  showLoading?: boolean;
  handleError?: boolean;
  withToken?: boolean;
}

export interface RequestError extends Error {
  config: RequestConfig;
  code?: string | number;
  isAxiosError: boolean;
  response?: AxiosResponse<ResponseData>;
}

class Request {
  private instance: AxiosInstance;
  private userStore = useUserStore();

  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config);
    this.setupInterceptors();
  }

  // 请求与响应拦截器
  private setupInterceptors() {
    this.instance.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        const token = this.userStore.token;
        if (token && (config as RequestConfig).withToken !== false) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      (error: AxiosError) => {
        return Promise.reject(error);
      }
    );

    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        const res = response.data;
        if (res.code === 200) {
          return res;
        } else {
          return Promise.reject({
            code: res.code,
            message: res.message || "业务错误",
            response,
          });
        }
      },
      (error: AxiosError<ResponseData>) => {
        const err: RequestError = {
          ...error,
          name: "RequestError",
          message: error.message || "网络错误",
          config: error.config as RequestConfig,
          isAxiosError: true,
        };

        if (error.response) {
          switch (error.response.status) {
            case 400:
              err.message = "请求参数错误";
              break;
            case 401:
              err.message = "未授权，请重新登录";
              break;
            case 403:
              err.message = "拒绝访问";
              break;
            case 404:
              err.message = "请求资源不存在";
              break;
            case 500:
              err.message = "服务器内部错误";
              break;
            default:
              err.message = `未知错误 (${error.response.status})`;
          }
        }

        if ((err.config as RequestConfig).handleError !== false) {
          console.error("[Request Error]:", err.message);
        }

        return Promise.reject(err);
      }
    );
  }

  public request<T = any>(config: RequestConfig): Promise<ResponseData<T>> {
    return this.instance.request(config);
  }

  public get<T = any>(
    url: string,
    config?: RequestConfig
  ): Promise<ResponseData<T>> {
    return this.request<T>({ ...config, method: "GET", url });
  }

  public post<T = any>(
    url: string,
    data?: any,
    config?: RequestConfig
  ): Promise<ResponseData<T>> {
    return this.request<T>({ ...config, method: "POST", url, data });
  }
}

const service = new Request({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json;charset=UTF-8",
  },
});

export default service;
